<template>
  <el-card shadow="never" :body-style="{padding:'15px 0 '}">
    <div class="card-header">
      <div class="column"></div>
      <span style="font-size: 18px">产品基本信息</span>
    </div>
    <el-form label-width="120px" ref="formRef" :model="stateForm" :rules="stateRulesForm">
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="stateForm.productName"/>
      </el-form-item>
      <el-form-item label="产品URL" prop="requestUrl">
        <el-input v-model="stateForm.requestUrl"/>
      </el-form-item>
      <el-form-item label="所属机构" prop="institutionId">
        <el-select v-model="stateForm.institutionId">
          <el-option v-for="item in institutionList" :key="item.name" :label="item.name"
                     :value="item.institutionId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属贷超APP" prop="appId">
        <el-select v-model="stateForm.appId" :disabled="type === 'edit'">
          <el-option v-for="item in productList" :key="item.appId" :label="item.appName"
                     :value="item.appId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品LOGO" prop="logoUrl">
        <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            ref="upload"
            action="#"
            accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG"
            :http-request="uploadChange"
        >
          <i v-if="!stateForm.logoUrl" class="el-icon-plus avatar-uploader-icon"></i>
          <img v-else style="width: 100%;height: 100%" :src="stateForm.logoUrl">
        </el-upload>
      </el-form-item>
      <el-form-item label-width="120px" label="产品详情页模板" prop="templateType">
        <el-radio-group v-model="stateForm.templateType">
          <el-radio v-for="(item,index) in srcList" :key="item" :label="index" style="margin-top: 15px">
            <div style="height:150px;width:80px;margin-top: 10px">
              <el-image
                  style="width: 100%; height: 100%"
                  :src="item"
                  :preview-src-list="srcList"
                  :initial-index="index"
              >
              </el-image>
            </div>
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="添加标签">
        <el-tag
            style="margin-right: 15px"
            :key="tag"
            v-for="tag in tagsState.dynamicTags"
            closable
            :disable-transitions="false"
            @close="tagsState.handleClose(tag)">
          {{ tag }}
        </el-tag>
        <el-input
            style="width: 150px"
            v-if="tagsState.inputVisible"
            v-model="tagsState.inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter="tagsState.handleInputConfirm"
            @blur="tagsState.handleInputConfirm"
        >
        </el-input>
        <el-button v-else v-show="tagsState.dynamicTags.length <= 2" class="button-new-tag" size="small"
                   @click="tagsState.showInput">+ 添加标签
        </el-button>
      </el-form-item>
      <el-form-item label="贷款额度范围" prop="loanMinLimit">
        <el-input style="width: 150px;display: inline-block" v-model="stateForm.loanMinLimit"
                  oninput="value = value.replace(/[^\d]/g, '')"/>
        <span style="padding: 0 10px">-</span>
        <el-input style="width: 150px;display: inline-block" v-model="stateForm.loanMaxLimit"
                  oninput="value = value.replace(/[^\d]/g, '')"/>
      </el-form-item>
      <el-form-item label="贷款金额提示文案" prop="amountDescribe" label-width="140px">
        <el-input type="textarea" :rows="3" v-model="stateForm.amountDescribe"/>
      </el-form-item>
      <el-form-item label="借款周期单位" prop="loanTermType">
        <el-radio :label="1" v-model="stateForm.loanTermType">天</el-radio>
        <el-radio :label="2" v-model="stateForm.loanTermType">月</el-radio>
      </el-form-item>
      <el-form-item label="可借周期" prop="loanMinTerm">
        <el-input style="width: 150px;display: inline-block" v-model="stateForm.loanMinTerm"
                  oninput="value = value.replace(/[^\d]/g, '')"/>
        <span style="padding: 0 10px">-</span>
        <el-input style="width: 150px;display: inline-block" v-model="stateForm.loanMaxTerm"
                  oninput="value = value.replace(/[^\d]/g, '')"/>
        <span style="margin-left: 5px">{{ stateForm.loanTermType === 1 ? '天' : '月' }}</span>
      </el-form-item>
      <el-form-item label="贷款期限提示文案" prop="termDescribe" label-width="140px">
        <el-input type="textarea" :rows="4" v-model="stateForm.termDescribe"/>
      </el-form-item>
      <el-form-item label="允许最大利息" prop="maxInterest">
        <el-input v-model.number="stateForm.maxInterest">
          <template #append>%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="允许最大日罚息" prop="maxDayInterest">
        <el-input v-model.number="stateForm.maxDayInterest">
          <template #append>%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="允许最大手续费" prop="maxFee">
        <el-input v-model.number="stateForm.maxFee">
          <template #append>%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="分期数" prop="periods">
        <el-input v-model.number="stateForm.periods"/>
      </el-form-item>
      <el-form-item label="支持展期" v-if="stateForm.periods  === 1" prop="isRollover">
        <el-radio :label="1" v-model="stateForm.isRollover">是</el-radio>
        <el-radio :label="0" v-model="stateForm.isRollover">否</el-radio>
      </el-form-item>
      <el-form-item v-if="type === 'add'" label="每次要单量(单位/单)" label-width="150px" prop="orderNum">
        <el-input v-model="stateForm.orderNum" style="width: 120px" oninput="value = value.replace(/[^\d]/g, '')"/>
        <el-checkbox style="margin-left: 15px" :true-label="1" :false-label="0" v-model="stateForm.orderNumType">
          包含老客订单量
        </el-checkbox>
      </el-form-item>
      <div class="card-header">
        <span class="column"></span>
        <span style="font-size: 18px">收费项配置</span>
      </div>
      <p style="margin-left: 15px">基础收费</p>
      <el-form-item label="收费方式" prop="feeType">
        <el-radio v-model="stateForm.feeType" :label="1">CPA订单量</el-radio>
        <el-radio v-model="stateForm.feeType" :label="2">CPS放款量</el-radio>
      </el-form-item>
      <el-form-item label="费用计算" prop="cpsFeeType" v-if="stateForm.feeType === 2">
        <el-radio v-model="stateForm.cpsFeeType" :label="1">按订单</el-radio>
        <el-radio v-model="stateForm.cpsFeeType" :label="2">按放款手续费比例</el-radio>
      </el-form-item>
      <el-form-item label="收费阶段" prop="feeStage" v-if="stateForm.feeType === 1">
        <el-radio v-model="stateForm.feeStage" :label="1">一推</el-radio>
        <el-radio v-model="stateForm.feeStage" :label="2">二推</el-radio>
      </el-form-item>
      <el-form-item :label="stateForm.cpsFeeType === 2 && stateForm.feeType === 2 ? '新客收费比例' : '新客收费单价' "
                    prop="feePrice">
        <el-input v-model="stateForm.feePrice" oninput="value = value.replace(/[^\d.]/g, '')">
          <template v-if="stateForm.cpsFeeType === 2 && stateForm.feeType === 2" #append>‰</template>
        </el-input>
      </el-form-item>
      <el-form-item :label="stateForm.cpsFeeType === 2 && stateForm.feeType === 2 ? '老客收费比例' : '老客收费单价' "
                    prop="oldFeePrice">
        <el-input v-model="stateForm.oldFeePrice" oninput="value = value.replace(/[^\d.]/g, '')">
          <template v-if="stateForm.cpsFeeType === 2 && stateForm.feeType === 2" #append>‰</template>
        </el-input>
      </el-form-item>
      <p style="margin-left: 15px">增值项收费</p>
      <el-form-item label="运营商数据">
        <el-radio v-model="stateForm.operatorFeeType" :label="1">要</el-radio>
        <el-radio v-model="stateForm.operatorFeeType" :label="0">不要</el-radio>
      </el-form-item>
      <el-form-item label="运营商数据收费单价" prop="operatorFee" label-width="150px" v-if="stateForm.operatorFeeType === 1">
        <el-input v-model="stateForm.operatorFee" oninput="value = value.replace(/[^\d.]/g, '')"/>
      </el-form-item>
    </el-form>
  </el-card>

</template>

<script>
import {reactive, ref, nextTick, watchEffect, watch, toRefs} from 'vue'
import {selectInstitution, uploadImage, selectProductList} from '@/api'
import {increaseProduct, updateProduct} from '@/api/product'
import {ElMessage} from "element-plus";

export default {
  name: "ProductEdit",
  props: {
    type: String,
    productInfo: Object,
    visible: Boolean
  },
  setup(props) {
    const saveTagInput = ref(null)
    const formRef = ref(null)
    const state = reactive({
      stateForm: {
        feeStage: 1,
        feeType: 1,
        isRollover: 0,
        loanTermType: 1,
        operatorFeeType: 1,
        cpsFeeType: 1,
        feePrice: null,
        operatorFee: null,
        loanMinLimit: null,
        loanMaxLimit: null,
        loanMaxTerm: null,
        loanMinTerm: null,
        logoUrl: null,
        institutionId: null,
        requestUrl: null,
        productName: null,
        oldFeePrice: null,
        periods: null,
        orderNum: null,
        maxInterest: null,
        maxDayInterest: null,
        maxFee: null,
        amountDescribe: null,
        termDescribe: null,
        appId: null
      },
      institutionList: [],
      srcList: [
        'https://ddhkapps.oss-cn-hongkong.aliyuncs.com/loan_yundun/1_220701150853_productCard.png',
        'https://ddhkapps.oss-cn-hongkong.aliyuncs.com/loan_yundun/1_220701150948_productCard.png',
        'https://ddhkapps.oss-cn-hongkong.aliyuncs.com/loan_yundun/1_220701151007_productCard.png',
        'https://ddhkapps.oss-cn-hongkong.aliyuncs.com/loan_yundun/1_220701151029_productCard.png',
        'https://ddhkapps.oss-cn-hongkong.aliyuncs.com/loan_yundun/1_220701151045_productCard.png',
        'https://ddhkapps.oss-cn-hongkong.aliyuncs.com/loan_yundun/1_220701151111_productCard.png',
        'https://ddhkapps.oss-cn-hongkong.aliyuncs.com/loan_yundun/1_220701151129_productCard.png'
      ],
      productList: []
    })
    const stateRulesForm = {
      productName: [
        {required: true, message: '请输入产品名称', trigger: 'blur'}
      ],
      requestUrl: [
        {required: true, message: '请输入产品链接', trigger: 'blur'}
      ],
      institutionId: [
        {required: true, message: '请选择机构方', trigger: 'change'}
      ],
      feePrice: [
        {required: true, message: '请输入新客收费单价', trigger: 'blur'}
      ],
      oldFeePrice: [
        {required: true, message: '请输入老客收费单价', trigger: 'blur'}
      ],
      loanMinLimit: [
        {required: true, message: '请输入贷款额度范围', trigger: 'blur'},
        {
          required: true, validator: (rule, value, callback) => {
            const {loanMinLimit, loanMaxLimit} = state.stateForm
            if (loanMinLimit && loanMaxLimit) {
              if (parseInt(loanMinLimit) > parseInt(loanMaxLimit)) {
                return callback(new Error('请输入正确的额度范围'))
              }
            }
            return callback()
          }
        }
      ],
      loanMinTerm: [
        {required: true, message: '请输入贷款可借周期', trigger: 'blur'},
        {
          required: true, validator: (rule, value, callback) => {
            const {loanMinTerm, loanMaxTerm} = state.stateForm
            if (loanMinTerm && loanMaxTerm) {
              if (parseInt(loanMinTerm) > parseInt(loanMaxTerm)) {
                return callback(new Error('请输入正确的可借周期'))
              }
            } else {
              return callback(new Error('请输入正确的周期区间'))
            }
            return callback()
          }, trigger: 'blur'
        }
      ],
      operatorFee: [
        {required: true, message: '请输入单价', trigger: 'blur'}
      ],
      orderNum: {required: true, message: '请输入', trigger: 'blur'},
      periods: [
        {required: true, message: '请输入分期数', trigger: 'blur'}
      ],
      maxDayInterest: {required: true, message: '请输入', trigger: 'blur'},
      maxFee: {required: true, message: '请输入', trigger: 'blur'},
      maxInterest: {required: true, message: '请输入', trigger: 'blur'},
      logoUrl: [
        {required: true, message: '请上传产品logo', trigger: 'blur'}
      ],
      appId: [
        {required: true, message: '请选择APP', trigger: 'change'}
      ],
      templateType: [
        {required: true, message: '请选择产品模板', trigger: 'change'}
      ]
    }
    const tagsState = reactive({
      dynamicTags: [],
      inputValue: null,
      inputVisible: false,
      showInput: () => {
        tagsState.inputVisible = true;
        nextTick(() => {
          saveTagInput.value.$refs.input.focus();
        });
      },
      handleClose: (tag) => {
        tagsState.dynamicTags.splice(tagsState.dynamicTags.indexOf(tag), 1);
      },
      handleInputConfirm: () => {
        let inputValue = tagsState.inputValue
        if (inputValue) {
          tagsState.dynamicTags.push(inputValue);
        }
        tagsState.inputVisible = false;
        tagsState.inputValue = '';
      },
    })
    const getSelect = () => {
      selectInstitution().then(res => {
        if (res.code === 200) {
          state.institutionList = res.data
        }
      })
      selectProductList().then(res => {
        if (res.code === 200) {
          state.productList = res.data
        }
      })
    }

    watch(() => props.visible, (value) => {
      if (value) {
        getSelect()
      }
    }, {immediate: true})
    watch(() => props.productInfo, (value) => {
      if (props.type === 'edit') {
        const {
          label, labelTwo, labelThree,
          feeStage,
          feeType,
          isRollover,
          loanTermType,
          feePrice,
          operatorFee,
          loanMinLimit,
          loanMaxLimit,
          loanMaxTerm,
          loanMinTerm,
          logoUrl,
          institutionId,
          requestUrl,
          productName,
          periods,
          operatorFeeType,
          oldFeePrice,
          orderNum,
          productId,
          cpsFeeType,
          maxFee,
          maxInterest,
          maxDayInterest,
          amountDescribe,
          termDescribe,
          appId,
          templateType
        } = props.productInfo
        state.stateForm = {
          oldFeePrice,
          operatorFeeType,
          feeStage,
          feeType,
          isRollover,
          loanTermType,
          feePrice,
          operatorFee: parseFloat(operatorFee || 0),
          loanMinLimit,
          loanMaxLimit,
          loanMaxTerm,
          loanMinTerm,
          logoUrl,
          institutionId,
          requestUrl,
          productName,
          periods,
          orderNum,
          productId,
          amountDescribe,
          termDescribe,
          appId,
          templateType,
          cpsFeeType: cpsFeeType || 1,
          maxFee: maxFee * 100 || null,
          maxInterest: maxInterest * 100 || null,
          maxDayInterest: maxDayInterest * 100 || null,
        }
        tagsState.dynamicTags = [label, labelTwo, labelThree].filter(item => item)
      }
    }, {immediate: true})

    const clearForm = () => {
      state.stateForm = {
        feeStage: 1,
        feeType: 1,
        isRollover: 0,
        loanTermType: 1,
        operatorFeeType: 1,
        cpsFeeType: 1,
        feePrice: null,
        operatorFee: null,
        loanMinLimit: null,
        loanMaxLimit: null,
        loanMaxTerm: null,
        loanMinTerm: null,
        logoUrl: null,
        institutionId: null,
        requestUrl: null,
        productName: null,
        oldFeePrice: null,
        periods: null,
        orderNum: null,
        maxInterest: null,
        maxDayInterest: null,
        maxFee: null,
        amountDescribe: null,
        termDescribe: null,
      }
      tagsState.dynamicTags = []
      formRef.value.resetFields()
    }
    const submitForm = () => {
      return new Promise((resolve, reject) => {
        formRef.value.validate(async v => {
          if (v) {
            const api = ((params) => props.type === 'add' ? increaseProduct(params) : updateProduct(params))
            const [label, labelTwo, labelThree] = tagsState.dynamicTags
            const {feePrice, oldFeePrice} = state.stateForm
            const res = await api({
              ...state.stateForm,
              appName: state.productList.find(item => item.appId === state.stateForm.appId).appName,
              label: label || '', labelTwo: labelTwo || '', labelThree: labelThree || '',
              updateType: 1,
              feePrice: parseFloat(feePrice),
              oldFeePrice: parseFloat(oldFeePrice),
            })
            if (res.code === 200) {
              ElMessage.success({
                message: props.type === 'add' ? '添加成功' : '编辑成功'
              })
              resolve(true)
            } else {
              reject(false)
            }
          }
        })
      })
    }
    // 上传图片
    const uploadChange = async (data) => {
      const formData = new FormData()
      formData.append('file', data.file)
      formData.append('type', 0)
      const res = await uploadImage(formData)
      if (res.code === 200) {
        state.stateForm.logoUrl = res.data
      }
    }
    return {
      tagsState,
      saveTagInput,
      ...toRefs(state),
      clearForm,
      stateRulesForm,
      submitForm,
      formRef,
      uploadChange
    }
  }
}
</script>

<style lang="less" scoped>
.card-header {
  padding: 15px 10px;

  .column {
    display: inline-block;
    height: 25px;
    width: 5px;
    background-color: #409eff;
    margin-right: 10px;
    padding-top: 5px;
    float: left;
    box-sizing: border-box;
  }
}
</style>
